package com.liuyucheng.designpattern.单例模式;

/**
 * 懒汉式
 * 线程不安全
 * 可以在方法上加synchronized，但是效率会比较低，更好的方法是加双检锁
 */
public class Singleton2 {
    //不加volatile，可能会发生指令重排，导致双检锁失效
    private static volatile Singleton2 singleton;

    //当被调用时才动态实例化
    public static Singleton2 getInstance() {
        if(singleton == null) {
            singleton = new Singleton2();
        }
        return singleton;
    }

    ///////////////////////////线程安全处理
    /**
     * 加synchronized
     * @return
     */
    public static synchronized Singleton2 getInstance2() {
        if(singleton == null) {
            singleton = new Singleton2();
        }
        return singleton;
    }

    /**
     * 双检锁单例模式
     * @return
     */
    public static Singleton2 getInstance3() {
        if(singleton == null) {
            synchronized (Singleton2.class) {
                if(singleton==null) {
                    singleton = new Singleton2();
                }
            }
        }
        return singleton;
    }
}
